/**
 * @file base_http_client.cpp
 * @author zeeland
 * @brief bulid clint to get data from server, then analysis to json
 * @version 0.1
 * @date 2022-04-17
 * 
 * @copyright Copyright (c) 2022
 * 
 */
#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <ESP8266WiFiMulti.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <ArduinoJson.h>

ESP8266WiFiMulti WiFiMulti;
WiFiClient client;
HTTPClient http;
#define server_url "http://101.33.214.83:8086/hello"

void jsonAnalysis(String input){
  StaticJsonDocument<96> doc;

  DeserializationError error = deserializeJson(doc, input);

  if (error) {
    Serial.print(F("deserializeJson() failed: "));
    Serial.println(error.f_str());
    return;
  }

  const char* msg = doc["msg"]; // "success"
  const char* data = doc["data"]; // "Hello World"
  int code = doc["code"]; // 200
  Serial.println();
  Serial.print("msg = ");Serial.println(msg);
  Serial.print("data = ");Serial.println(data);
  Serial.print("code = ");Serial.println(code);
}

void clientInit(){
  if ((WiFiMulti.run() == WL_CONNECTED)) {
      Serial.print("[HTTP] begin...\n");
      if (http.begin(client, server_url)) {  // HTTP

        Serial.print("[HTTP] GET...\n");
        // start connection and send HTTP header
        int httpCode = http.GET();

        // httpCode will be negative on error
        if (httpCode > 0) {
          // HTTP header has been send and Server response header has been handled
          Serial.printf("[HTTP] GET... code: %d\n", httpCode);

          // file found at server
          if (httpCode == HTTP_CODE_OK || httpCode == HTTP_CODE_MOVED_PERMANENTLY) {
            String payload = http.getString();
            jsonAnalysis(payload);
            Serial.println(payload);
          }
        } else {
          Serial.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
        }

        http.end();
      } else {
        Serial.printf("[HTTP} Unable to connect\n");
      }
    }

}

void setup() {

  Serial.begin(115200);
  // Serial.setDebugOutput(true);

  Serial.println();
  Serial.println();
  Serial.println();

  for (uint8_t t = 4; t > 0; t--) {
    Serial.printf("[SETUP] WAIT %d...\n", t);
    Serial.flush();
    delay(1000);
  }

  WiFi.mode(WIFI_STA);
  WiFiMulti.addAP("laptop_zeeland_5592", "12345678");

}

void loop() {
  clientInit();
  delay(1000);
}